package main

import (
	"flag"
	"fmt"
	"github.com/hashicorp/consul/api"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"rpc_demo/user_srv/global"
	"rpc_demo/user_srv/handler"
	"rpc_demo/user_srv/initialize"
	"rpc_demo/user_srv/proto"
	"syscall"
)

func main() {

	initialize.InitViperLogger()
	initialize.InitConfig()
	initialize.InitMysqlDb()

	IP := flag.String("ip", global.ServiceConfig.Host, "ip地址")
	Port := flag.Int("port", global.ServiceConfig.Port, "端口地址")

	server := grpc.NewServer()
	//注册consul健康检查
	grpc_health_v1.RegisterHealthServer(server, health.NewServer())

	// ----------------------- 1. 注册consul服务 -----------------------
	// 1、初始化consul配置
	consulConfig := api.DefaultConfig()
	// consulConfig.Address = "127.0.0.1:8500"  // consul服务的默认地址可省略，如果不是本机，需要补充
	client, err := api.NewClient(consulConfig)
	if err != nil {
		zap.S().Error("初始化consule失败：", err.Error())
		return
	}

	//健康检查配置
	//check := &api.AgentServiceCheck{
	//	GRPC:                           "127.0.0.1:8021/health",
	//	Timeout:                        "5s", //超时
	//	Interval:                       "5s", //间隔时间
	//	DeregisterCriticalServiceAfter: "10s",
	//}

	registration := new(api.AgentServiceRegistration)
	registration.Name = global.ServiceConfig.Name
	//registration.ID = global.ServiceConfig.Name
	serverId := uuid.NewV4().String()
	registration.ID = serverId
	registration.Address = "127.0.0.1"
	registration.Port = *Port
	registration.Tags = []string{"user-srv"}
	//registration.Check = check //健康检查

	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		zap.S().Error("consul注册失败：", err.Error())
		return
	}
	// ----------------------- 注册consul服务 -----------------------

	proto.RegisterUserServer(server, &handler.UserServer{})
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *IP, *Port))
	if err != nil {
		panic(err)
	}
	go func() {
		err = server.Serve(listen)
		if err != nil {
			panic(err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = client.Agent().ServiceDeregister(serverId); err != nil {
		zap.S().Error("注销失败")
	}
	zap.S().Error("注销成功")
}
